package org.bigk.invoices.interceptors;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bigk.invoices.utils.SessionUtils;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AuthInterceptor implements Interceptor {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(AuthInterceptor.class);

	private static final long serialVersionUID = 0x3bd05f881b3907ddL;

	public AuthInterceptor() {
	}

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation actionInvocation) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("intercept(ActionInvocation actionInvocation="
					+ actionInvocation + ") - start");
		}

		String namespace = actionInvocation.getProxy().getNamespace();
		String actionName = actionInvocation.getProxy().getActionName();
		String method = actionInvocation.getProxy().getMethod();
		
		if (logger.isDebugEnabled()) {
			logger.debug("intercept(ActionInvocation) - namespace=" + namespace + ", actionName=" + actionName + ", method=" + method);
		}
		
		String returnString = null;
		
		// interceptor called before action has been executed
		Map<String, Object> session =
			actionInvocation.getInvocationContext().getSession();

		boolean isAuthenticated = SessionUtils.isLoggedIn(session);
		if (logger.isDebugEnabled()) {
			logger.debug("intercept(ActionInvocation) - wartosc flagi z sesji - isAuthenticated=" + isAuthenticated);
		}

		// if not authenticated, we can allow only access to 'unsecured' namespace
		if (!isAuthenticated) {
			isAuthenticated = StringUtils.equals("/unsecured", namespace);
			if (logger.isDebugEnabled()) {
				logger.debug("intercept(ActionInvocation) - wartosc flagi dla namespace '/unsecured' - isAuthenticated=" + isAuthenticated);
			}
		}

		if (!isAuthenticated) {
			Object action = actionInvocation.getAction();
			if (logger.isDebugEnabled()) {
				logger.debug("intercept(ActionInvocation) - action=" + action);
			}

			if (action != null && (action instanceof ActionSupport)) {
				ActionSupport actionSupport = (ActionSupport) action;
				actionSupport.addActionError(
						actionSupport.getText("errors.sessionExpired"));
			}

			returnString = "login";
		}
		
		if (StringUtils.isEmpty(returnString)) {
			returnString = actionInvocation.invoke();
		}
		
		if (logger.isDebugEnabled()) {
			logger.debug("intercept(ActionInvocation) - end - return value=" + returnString);
		}
		return returnString;
	}
}
